import base64
import hmac
import time
from _sha1 import sha1
from urllib import parse

from grafana_webhook.settings import HMAC_KEY


def gen_hmac(data):
    token = hmac.new(data.encode(), HMAC_KEY.encode(), sha1).digest()
    token = base64.b64encode(token)
    return token


def get_auth_header(method, path):
    separator = "-"
    now_time = int(round(time.time() * 1000))
    data = method + separator + str(now_time) + separator + path
    token = gen_hmac(data)
    return {'Date': str(now_time), 'Authorization': token}


def get_url_path(url):
    """
	获取url中的路径
	"""
    try:
        path = parse.urlparse(url).path
        return path if path else ''
    except Exception as e:
        return ''

# auth_header = get_auth_header('GET', get_url_path(request_url))
# headers = {
#     "Connection": "close",
#     "Date": auth_header['Date'],
#     "Authorization": auth_header['Authorization']
# }
